<template>
    <wsPage title="添加banner推荐">
        <div slot="page_operate">
			<Button><Icon></Icon><span @click="goBack">返回</span></Button>
		</div>       
        <wsSmPanel :page="table.page" @page-change="serachPageListData" style="margin-bottom:50px;">
             <!-- 添加banner -->
            <div slot="add_banner" class="add_banner_content" style="padding-bottom:10px;">
                <Form :label-width="100" >
					<FormItem label="主图" required>
                        <!-- <div style="width: 420px;height:250px;border:1px solid #ccc;float:left;" class="left-side" >
                            <div :style="{backgroundImage:'url('+form.upload.imgData+')',backgroundRepeat:'no-repeat', backgroundPosition:'center center', backgroundSize: '100% auto',width:'100%',height:'100%'}"></div>
                           
                            <ws-upload-cos ref="upload" catelog="merchants" :cfile-key="form.upload.fileKey" :show-upload-list="false" :format="['jpg','jpeg','png']" :max-size="2048" :on-success="uploadSuccess" type="drag">
                                <Button>添加图片</Button>
                            </ws-upload-cos>
                            
                            <div>只支持JPG .PNG格式(16:9)</div>
                        </div>  -->
                        <ws-upload-cos ref="coverUpload" catelog="topic" :show-upload-list="false" :format="['jpg','jpeg','png']" :max-size="2048" :on-success="uploadCoverSuccess" :auto-upload="false" :on-file-list="uploadCoverFileList">
                            <div class="ws-middle" :style="positionStyle" style="border: 1px solid #ccc;cursor: pointer;">
                                <span v-if="cropper.datas.cover.base64 == ''">封面图片</span>
                                <img :src="cropper.datas.cover.base64" :style="positionStyle" v-if="cropper.datas.cover.base64 != ''"/>
                            </div>
                        </ws-upload-cos>
                        <span style="color:red">图片尺寸比例为{{cropper.config.fixedNumber}}</span>

			        </FormItem>

                    <FormItem label="语言" required style="margin-top:40px;">
                        <Select style="width: 30%;" v-model="addBannerData.languageCode" @on-change="changeLanguage">
                            <Option :value="item.code" v-for="(item,index) in (modal2.fields.languages)" v-bind:key="index">{{item.motherTongue}}</Option>
                        </Select>
			        </FormItem>   

                    <FormItem label="类型" required >
                        <Select style="width: 30%;" v-model="addBannerData.type" @on-change="changeType">
                            <Option :value="item.type" v-for="(item,index) in addBannerType" v-bind:key="index">{{item.name}}</Option>
                        </Select>
                    </FormItem>
                   
					<FormItem label="名称"  required>
			            <Input  placeholder="请输入" style="width: 30%;" v-model="queryPanel.goods.name"/>
			        </FormItem>
                 
                     <FormItem label="商户名称" v-if="addBannerData.type==4">
                            <Input v-model="queryPanel.goods.shop" placeholder="请输入" style="width: 30%;" />
                        </FormItem>
                        <FormItem label="品牌" v-if="addBannerData.type==4">
                            <Select v-model="queryPanel.goods.brandId" filterable clearable placeholder="请输入搜索查询" style="width: 30%;">
                                <Option v-for="item in queryPanel.fields.brands" :value="item.id" :key="item.id">{{ item.name }}</Option>
                            </Select>
                        </FormItem>
                        <FormItem label="发布类型" v-if="addBannerData.type==4">
                            <Select clearable v-model="queryPanel.goods.promotionStatus" placeholder="请选择" class="ws-form-select">
                                <Option value="0">上新</Option>
                                <Option value="1">折扣</Option>
                            </Select>
                        </FormItem>
                        <FormItem label="销售类型" v-if="addBannerData.type==4">
                            <Select clearable v-model="queryPanel.goods.saleType" placeholder="请选择" class="ws-form-select">
                                <Option value="1">现货</Option>
                                <Option value="2">预售</Option>
                            </Select>
                        </FormItem>
                         
				</Form>               
            </div> 
            <div slot="list_operate">              
               <Button @click="searchData">搜索</Button>
            </div>
           <!-- 提交数据 --> 
           <div slot="list_data">
				<ws-table :data="table.data" style="width: 100%" ref="table"  @select="chooseHandleChange" @select-all="selectAllDisabled" v-if="addBannerData.type!=4">
                     <ws-table-column align="center" type="selection" width="80" fixed="left" ></ws-table-column>
                     <ws-table-column  label="图片" min-width="180" align="center">
                        <template slot-scope="scope">
                            <img :src="scope.row.imgUrl" alt="" style="width:160px;height:90px;">
                        </template>
                    </ws-table-column>
                    <ws-table-column  label="名称" min-width="180" align="center">
                        <template slot-scope="scope">
                            <span>{{scope.row.name}}</span>
                        </template>
                    </ws-table-column>
				</ws-table>
                <!-- 商品 -->
                <ws-table :data="table.data" style="width: 100%" ref="table"  @select="chooseHandleChange" @select-all="selectAllDisabled" v-if="addBannerData.type==4">
                     <ws-table-column align="center" type="selection" width="80" fixed="left" ></ws-table-column>
                     <ws-table-column  label="图片" min-width="180" align="center">
                        <template slot-scope="scope">
                            <img :src="scope.row.primaryPicUrl" alt="" style="width:160px;height:90px;">
                        </template>
                    </ws-table-column>
                    <ws-table-column  label="名称" min-width="180" align="center">
                        <template slot-scope="scope">
                            <span>{{scope.row.productName}}</span>
                        </template>
                    </ws-table-column>
				</ws-table>
           </div>                            
        </wsSmPanel>
        <ws-cropper v-model="cropper.show" :img="cropper.imgData" :config="cropper.config" @crop-ok="cropOk"></ws-cropper>
        <!-- 确认/取消 -->
        <Button type="success" @click="confirm" size="large"  style="position:absolute;left:50%;bottom:25px;">确认</Button> 
    </wsPage>   
</template>

<script>
import Util from '../../../common/util.js';
import FileUtil from '../../../common/file.js';
import 'dplayer/dist/DPlayer.min.css';
import DPlayer from 'dplayer';
import $ from 'jquery';
import m from 'malihu-custom-scrollbar-plugin';
import mw from 'jquery-mousewheel';
import 'malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar.css';

export default {
    data(){
        return {
            table: {
                data: [],
                page: {
                    total: 0, //总条数
                    pageNum: 1, //当前页
                    pageSize: 5 //每页显示条数
                }
            },
            addBannerData:{
                imgUrl:'',
                name:'',
                type:2,
                languageCode:'zh',
                selectionList:{}
            },
            addBannerType:[
                {
                    type:1,
                    name:'活动'
                },
                {
                    type:2,
                    name:'主题'
                },
                {
                    type:3,
                    name:'店铺'
                },
                {
                    type:4,
                    name:'商品'
                },
            ],
            modal2: { 
                fields: {
                    languages: []
                }
            },
            form: {
                upload: {
                    fileKey: "",
                    imgData:'',
                    imgUrl:''
                }
            },

            cropper: {
                show: false,
                datas: {
                    top: {
                        base64: ''
                    },
                    cover: {
                        base64: ''
                    }
                },
                config: {
                    fixedNumber: [27, 20],
                    // 只有自动截图开启 宽度高度才生效
                    autoCropWidth: 375,
                    autoCropHeight: 278,
                }
            },
            // banner---商品          
            queryPanel: {
                goods:{
                    name: '',
                    promotionStatus: '',
                    saleType: '',
                    shop: '',
                    brandId: ''
                },
                fields: {
                    brands: []
                },
             }

        }
    },
    computed: {
       /**
         * 计算样式
         */
        positionStyle() {
            return 'width:' + this.cropper.config.autoCropWidth + 'px;height:' + this.cropper.config.autoCropHeight + 'px;'
        }
    },
    mounted() {
        this.initLanguages();
        this.initBrands();
        // this.getBannerTypeDataList();
    },
    methods:{
			/**
			 * 初始化可翻译的语言列表
			 */
			initLanguages() {
				let _this = this;
				this.axios.get('/ws/ops/v2/languages/translatable').then(response => {
					var res = response.data;
					var resMeta = res.meta;
                    // 语言列表
                    console.log(res.data)
					if (0 == resMeta.code) {
						_this.modal2.fields.languages = res.data;
					} else {
						_this.$Message.warning(resMeta.message);
					}
				});
            },	
            /**
			 * 初始化品牌列表
			 */
			initBrands() {
				const _this = this;
				this.axios.get('/ws/ops/brands').then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if(0 == resMeta.code) {
						_this.queryPanel.fields.brands = res.data;
					} else {
						_this.$Message.warning('初始品牌失败:' + resMeta.message);
					}
				});
			},
           /**
            * 根据banner类型查询对应的数据列表  /ws/ops/recommend/banner/type/{pageNum}/{pageSize}?type=1&languageCode=zh
            */
            getBannerTypeDataList(){
                let _this=this;
                this.axios.get('/ws/ops/recommend/banner/type/'+_this.table.page.pageSize+'/'+_this.table.page.pageNum+'?type='+_this.addBannerData.type+'&languageCode='+_this.addBannerData.languageCode)
                    .then(response=>{
                        let res=response.data;
                        let resMeta=res.meta;
                        if(0==resMeta.code){
                            _this.table.data=res.data.list;
                            _this.table.page.total=res.data.total;
                            _this.table.page.pageNum=res.data.pageNum;
                            _this.table.page.pageSize=res.data.pageSize;
                        }else{
                            _this.$Message.warning(resMeta.message);
                        }
                    })

            },
            /**
             * 单选数据
             */
            chooseHandleChange(selection,row){
                this.$refs.table.clearSelection();
                this.addBannerData.selectionList=row;
                this.$refs.table.toggleRowSelection(row,true);
            },
            /**
             * 
             */
            selectAllDisabled(row){
                this.$refs.table.clearSelection();  
            },

            /**
             * 改变语言--切换banner类型查询对应的数据列表
             */
            changeLanguage(){
                this.table.page.total=0;
                this.table.page.pageNum=1;
                this.table.page.pageSize=10;
                // this.getBannerTypeDataList();
            },
            /**
             * 改变类型--切换banner类型查询对应的数据列表
             */
            changeType(){
                this.table.page.total=0;
                this.table.page.pageNum=1;
                this.table.page.pageSize=10;
                // this.getBannerTypeDataList();
                this.table.data=[];
            },  
            /**
             * 分页查询
             */
            serachPageListData(){
                this.getBannerTypeDataList();
                this.searchData();
            },

            /**
                提交验证数据
             */
            confirm(){
                var _this=this;
                let imgUrl=_this.cropper.datas.cover.base64;
                let name=_this.queryPanel.goods.name;
                // let orderNum=_this.addBannerData.orderNum;
                let type=_this.addBannerData.type;
                let languageCode=_this.addBannerData.languageCode;
                let selectionList=_this.addBannerData.selectionList;
                if(Util.vad.isBlank(imgUrl)){
                    this.$Message.info('请上传图片');
					return;
                } 
                else if(Util.vad.isBlank(name)){
                    this.$Message.info('请输入名称');
					return;
                }else if(Util.vad.isBlank(type)){
                    this.$Message.info('请选择类型');
					return;
                }else if(Util.vad.isBlank(languageCode)){
                    this.$Message.info('请选择语言');
					return;
                }else if(selectionList.length==0){
                    this.$Message.info('请选择内容');
					return;
                }
                this.contentDataConfirm();
            },
            /**
             * 内容验证不能为空
             */
            contentDataConfirm(){               
                var _this=this;
                _this.saveCoverImg();
               
            },

            /**
            图片上传成功保存地址url
             */
            // uploadSuccess(response, file, fileList) {
			// 	if(0 == response.meta.code) {
			// 		this.form.upload.fileKey = response.data.fileId;
            //      this.form.upload.imgData=response.data.Location;
			// 	}
			// },
			/**
             * 返回
             */
            goBack() {
    			this.$router.push({name: 'ops_reco_list'});
            },
            
            /**
			 * 封面图上传成功
			 */
			uploadCoverSuccess(response, file, fileList) {
				let _this = this;
				if(0 == response.meta.code) {
                    _this.form.upload.imgData=response.data.Location;    
                    if(_this.addBannerData.type!=4){
                        var postData = {
                            'imgUrl':_this.form.upload.imgData,
                            'name':_this.queryPanel.goods.name,                
                            'languageCode':_this.addBannerData.languageCode,
                            'type':_this.addBannerData.type,
                            'linkId':_this.addBannerData.selectionList.id
                        };
                    }else {
                        var postData = {
                            'imgUrl':_this.form.upload.imgData,
                            'name':_this.queryPanel.goods.name,                
                            'languageCode':_this.addBannerData.languageCode,
                            'type':_this.addBannerData.type,
                            'linkId':_this.addBannerData.selectionList.productId
                        };
                    }
                    
                    this.updateBannerBasic(postData, function() {
						_this.contentDataConfirm();
					});
				}
            },


            updateBannerBasic(postData, callback) {
                let _this=this;
                this.axios.post('/ws/ops/recommend/banner',postData).then(response=>{
                    let res=response.data;
                    let resMeta=res.meta;
                    console.log(res);
                    if(0==resMeta.code){                       
                        _this.$Message.info('添加成功');
                        // 跳转到banner页面
                        _this.$router.push('/recoManager');
                    }else {
                        _this.$Message.warning(resMeta.message)
                    }
                })
			},

            /**
			 * 封面图片
			 */
			uploadCoverFileList(fileList) {
				let _this = this;
				let newFile = fileList[0];
				FileUtil.readFile(newFile, function(result, currFile) {
					_this.addTopImg(result);
				});
            },
            
            /**
			 * 截图OK
			 */
			cropOk(data) {
				let action = data.action;
                let imgBase64Data = data.data;               
				this.cropper.datas.cover.base64 = imgBase64Data;
                this.cropper.imgData = data;

            },
            
            /**
			 * 添加顶部图片
			 */
			addTopImg(result) {
				this.cropper.imgData = result;
				this.cropper.show = true;
			},

            /**
			 * 保存封面图
			 */
			saveCoverImg() {
				let data = this.cropper.datas.cover.base64;
				let fileName = "topic_" + new Date().getTime() + '.jpg';
				let newFile = FileUtil.dataURLtoFile(data, fileName);
				this.$refs.coverUpload.execUpload([newFile]);
			},	

            // 当选择商品时--显示搜索条件
            searchData(){
                let _this=this;
                let pageSize = _this.table.page.pageSize;
				let pageNum = _this.table.page.pageNum;

                if(_this.addBannerData.type==4){
                     this.axios.get('/ws/ops/recommend/product/list/'+pageSize+'/'+pageNum,{
                        params: _this.queryPanel.goods
                    }).then(response=>{
                        let res=response.data;
                        console.log(res);
                        let resMeta=res.meta;
                        if(0==resMeta.code){
                            _this.table.data=res.data.list;
                            _this.table.page.total=res.data.total;
                            if(res.data.pageNum>1){
                                _this.table.page.pageNum=res.data.pageNum;
                            }else{
                                _this.table.page.pageNum=1;
                            }  
                            _this.table.page.pageNum=res.data.pageNum;
                        }else{
                            _this.$Message.warning(resMeta.message);
                        }
                    })
                }else{
                    _this.getBannerTypeDataList();
                }
               
            }


    }
}
</script>

<style>
    .add_banner_content{
        padding-top:10px;
    }
</style>

